import cv2 
import numpy as np 
from tracker_base import TrackerBase

import sys

from PyQt5.QtGui import QImage,QPixmap
from PyQt5.QtWidgets import QDialog,QApplication
from PyQt5.QtCore import QTimer
from PyQt5.uic import loadUi
from kfc_i import Ui_KFC

img3 = cv2.imread('Logo.jpg')
img3 = cv2.resize(img3, (40, 40))

img_pdsu = cv2.imread('img.jpg')
img_pdsu = cv2.resize(img_pdsu, (480, 640))

class KcfKalmanTracker(TrackerBase): 
    def __init__(self, window_name):
        super(KcfKalmanTracker, self).__init__(window_name)
        self.tracker = cv2.TrackerKCF_create()
        self.detect_box = None
        self.track_box = None
        self.kalman = cv2.KalmanFilter(4, 2)
        self.kalman.measurementMatrix = np.array([[1,0,0,0],[0,1,0,0]],np.float32)
        self.kalman.transitionMatrix = np.array([[1,0,1,0],[0,1,0,1],[0,0,1,0],[0,0,0,1]],np.float32)
        self.kalman.processNoiseCov = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]],np.float32)*0.03
        self.measurement = np.array((2,1),np.float32)
        self.prediction = np.array((2,1),np.float32)
    def process_image(self, frame):
        try:
            if self.detect_box is None:
                return frame
            src = frame.copy()
            if self.track_box is None or not self.is_rect_nonzero(self.track_box):
                self.track_box = self.detect_box
                if self.tracker is None:
                    raise Exception("tracker not init")
                status = self.tracker.init(src, self.track_box)
                if not status:
                    raise Exception("tracker initial failed")
            else:
                self.track_box = self.track(frame)
        except:
            pass
        #print("frame:",frame.shape[0],frame.shape[1],frame.shape[2])
        #frame=round_coord[0],round_coord[1]
        #frame[50:150, 50:150] =

        #frame[(round_x-10):(round_x+10), (round_y-10):(round_y+10)] = [200, 100, 100]

        return frame
    def track(self, frame):
        status, coord = self.tracker.update(frame)
        center = np.array([[np.float32(coord[0]+coord[2]/2)],[np.float32(coord[1]+coord[3]/2)]])
        self.kalman.correct(center)
        self.prediction = self.kalman.predict()
        cv2.circle(frame, (int(self.prediction[0]),int(self.prediction[1])),9,(205,120,100),2)
        round_coord = (int(coord[0]), int(coord[1]), int(coord[2]), int(coord[3]))
        #print("round_coord",round_coord[0],round_coord[1])
        #frame[(round_coord[0]-10):(round_coord[0]+10), (round_coord[1]-10):(round_coord[1]+10)] = [200, 100, 100]
       # cv2.rectangle(frame,(round_coord[0],),())
       # print(round_coord[0], round_coord[1], round_coord[2], round_coord[3])

        return round_coord






class Life2Coding(QDialog, Ui_KFC):
    def __init__(self, parent=None):
        super(QDialog,self).__init__(parent)
        self.setupUi(self)
        self.image = None
        self.open_button.clicked.connect(lambda:self.KFC_OPen())
        self.close_button.clicked.connect(lambda:self.KFC_Close())
        self.open_picture.clicked.connect(lambda:self.KFC_Picture())
        self.exit_sys.clicked.connect(lambda:self.KFC_Exit())

        self.cap=None
        self.status=0
        #self.kcfkalmantracker = KcfKalmanTracker('KCF')


    def KFC_OPen(self):
        self.status=1
        self.cap = cv2.VideoCapture(1)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(5)


    def update_frame(self):
        if self.status==1:
            ret, frame = self.cap.read()
            #frame[100:100 + 150, 100:100 + 150,:] = logo
            frame[64:104, 10:50] = img3
            x, y = frame.shape[0:2]
            print(x,y)
            xx=int(x/2)
            yy=int(y/2)
            frame[xx-12:xx+12, yy-3:yy+3] = [194,  194,22]
            frame[xx-3:xx+3,yy-12:yy+12] = [194, 194, 22]

            #rame[10:40, 20:60] = [194, 194, 22]
            cv2.putText(frame, 'PDSU' , (56, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 140, 255), 1)

            # small_frame = self.cv2.resize(frame, (int(y), int(x)))
            small_frame =cv2.resize(frame, (int(y), int(x)))

            #self.displayImage(kcfkalmantracker.process_image(small_frame), 1)

            self.displayImage(small_frame, 1)

    def displayImage(self, img, window=1):

        qformat = QImage.Format_Indexed8
        if (len(img.shape)) == 3:  # [0]=rows,[1]=cols,[2]=channels
            if img.shape[2] == 4:
                qformat = QImage.Format_RGBA8888
            else:
                qformat = QImage.Format_RGB888
        outImage = QImage(img, img.shape[1], img.shape[0], img.strides[0], qformat)
        # BGR->RGB
        outImage = outImage.rgbSwapped()

        if window == 1:
            self.video_cv.setPixmap(QPixmap.fromImage(outImage))
            self.video_cv.setScaledContents(True)


    def KFC_Close(self):
        if self.status == 1:
            self.cap.release()
        self.status = 0

    def KFC_Picture(self):
        if self.status == 1:
            self.cap.release()
        self.status = 0
        img_pdsu[10:60, 10:50] = [194, 10, 22]
        img_pdsu[64:104, 10:50] = img3

        self.displayImage(img_pdsu,1)


    def KFC_Exit(self):
        self.cap.release()
        sys.exit(app.exec_())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Life2Coding()
    window.setWindowTitle("图像覆盖")
    window.show()
    sys.exit(app.exec_())

